<template>
  <div class="leave-approval-container">
    <h2  >请假审批</h2>
    <!-- 查询区域：输入框与按钮分开 -->
    <!-- 查询区域：模仿员工管理页 -->
    <div class="search-container">
      <!-- 审批状态筛选 -->
      <el-select
          v-model="statusFilter"
          placeholder="审批状态"
          class="status-select"
          @change="getAllLeaves"
      >
        <el-option label="全部" value="" />
        <el-option label="待审批" value="待审批" />
        <el-option label="已审批" value="已审批" />
      </el-select>

      <!-- 员工姓名 -->
      <el-input
          v-model="searchName"
          placeholder="请输入员工姓名"
          class="search-input"
          clearable
      />

      <!-- 查询按钮：样式完全模仿员工页 -->
      <el-button
          type="success"
          plain
          class="search-button"
          @click="searchByName"

      >
        查询
      </el-button>

      <!-- 重置按钮 -->
      <el-button
          type="default"
          class="reset-button"
          @click="resetSearch"
      >
        重置
      </el-button>
    </div>

    <!-- 错误提示 -->
    <div class="error-message">{{ errorMessage }}</div>

    <!-- 请假表格 -->
    <el-table
        :data="leaveList"
        class="leave-table"
        header-cell-class-name="table-header"
        border
    >
      <el-table-column label="序号" type="index" width="90" align="center" />
      <el-table-column prop="employeeName" label="员工姓名" width="164" align="center" />
      <el-table-column
          prop="startDate"
          label="请假开始日期"
          width="150"
          align="center"
          :formatter="formatDate"
      />
      <el-table-column
          prop="endDate"
          label="请假结束日期"
          width="150"
          align="center"
          :formatter="formatDate"
      />
      <el-table-column prop="reason" label="请假原因" width="250" align="center" />
      <el-table-column prop="status" label="请假状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="statusTagType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button
              v-if="scope.row.status === '待审批'"
              type="primary"
              size="small"
              @click="showApproveDialog(scope.row.id)"
          >
            审批
          </el-button>
          <el-button
              v-else
              type="info"
              size="small"
              @click="showLeaveDetail(scope.row.id)"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageContains.pageNum"
          v-model:page-size="pageContains.pageSize"
          :page-sizes="[10,20,30,50,100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageContains.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 审批对话框 -->
    <el-dialog v-model="approveDialog" title="请假审批" width="500px">
      <el-form :model="curLeave" label-width="120px">
        <el-form-item label="员工姓名">
          <el-input v-model="curLeave.employeeName" disabled />
        </el-form-item>
        <el-form-item label="请假开始日期">
          <el-input v-model="curLeave.startDate" disabled />
        </el-form-item>
        <el-form-item label="请假结束日期">
          <el-input v-model="curLeave.endDate" disabled />
        </el-form-item>
        <el-form-item label="请假原因">
          <el-input v-model="curLeave.reason" disabled type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item
            label="审批决定"
            prop="decision"
            :rules="[{required:true,message:'请选择审批决定',trigger:'blur'}]"
        >
          <el-select v-model="curLeave.decision" placeholder="请选择">
            <el-option label="通过" value="通过" />
            <el-option label="未通过" value="未通过" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeApproveDialog">取消</el-button>
        <el-button type="primary" @click="optOne">确认审批</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog" title="请假详情" width="500px">
      <el-form :model="curLeave" label-width="120px">
        <el-form-item label="请假记录ID">
          <el-input v-model="curLeave.id" disabled />
        </el-form-item>
        <el-form-item label="员工ID">
          <el-input v-model="curLeave.employeeId" disabled />
        </el-form-item>
        <el-form-item label="员工姓名">
          <el-input v-model="curLeave.employeeName" disabled />
        </el-form-item>
        <el-form-item label="请假开始日期">
          <el-input v-model="curLeave.startDate" disabled />
        </el-form-item>
        <el-form-item label="请假结束日期">
          <el-input v-model="curLeave.endDate" disabled />
        </el-form-item>
        <el-form-item label="请假原因">
          <el-input v-model="curLeave.reason" disabled type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="审批状态">
          <el-tag :type="statusTagType(curLeave.status)">
            {{ curLeave.status }}
          </el-tag>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDetailDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/* ========== 原有 import 保持不变 ========== */
import { ref, reactive, onMounted } from 'vue'
import http from '@/axios/http'
import dayjs from 'dayjs'

/* -------------------- 数据 -------------------- */
const leaveList    = ref([])
const errorMessage = ref('')
const approveDialog= ref(false)
const detailDialog = ref(false)
const curLeave     = ref({})
const statusFilter = ref('')
const searchName   = ref('')
const pageContains = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

/* -------------------- 生命周期 -------------------- */
onMounted(() => getAllLeaves())

/* -------------------- 网络请求 -------------------- */
async function getAllLeaves() {
  try {
    const res = await http.post('/glsb/getAllLeaves', {
      pageNum:  pageContains.pageNum,
      pageSize: pageContains.pageSize,
      status:   statusFilter.value,
      employeeName: searchName.value
    })
    const r = res.data
    if (r.result === 'success') {
      pageContains.total = r.data.total
      const raw = r.data.list
      const names = await Promise.all(raw.map(item => getEmployeeName(item.employeeId)))
      const list = raw.map((t, i) => ({ ...t, employeeName: names[i] }))
      list.sort((a, b) => {
        const order = { '待审批': 0, '通过': 1, '不通过': 2 }
        return order[a.status] - order[b.status]
      })
      leaveList.value = list
    } else {
      errorMessage.value = r.error || '获取数据失败'
    }
  } catch (e) {
    errorMessage.value = `请求异常：${e.message}`
  }
}

async function getEmployeeName(id) {
  try {
    const res = await http.get(`/glsb/getEmployeeInfo?id=${id}`)
    return res.data.data?.name || '未知员工'
  } catch {
    return '未知员工'
  }
}

/* -------------------- 日期/搜索 -------------------- */
function formatDate(row, col) {
  return row[col.property] ? dayjs(row[col.property]).format('YYYY-MM-DD') : ''
}

async function searchByName() {
  pageContains.pageNum = 1
  await getAllLeaves()
}

/* -------------------- 重置 -------------------- */
async function resetSearch() {
  statusFilter.value = ''
  searchName.value   = ''
  pageContains.pageNum = 1
  await getAllLeaves()
  errorMessage.value = ''
}

/* -------------------- 弹窗控制 -------------------- */
function showApproveDialog(id) {
  getLeaveDetail(id).then(() => {
    approveDialog.value = true
    checkDateLegal()
  })
}
function showLeaveDetail(id) {
  getLeaveDetail(id).then(() => (detailDialog.value = true))
}
async function getLeaveDetail(id) {
  try {
    const res = await http.post('/glsb/getLeaveById', { id })
    const r  = res.data
    if (r.result === 'success') {
      curLeave.value = {
        ...r.data,
        decision: '',
        startDate: dayjs(r.data.startDate).format('YYYY-MM-DD'),
        endDate:   dayjs(r.data.endDate).format('YYYY-MM-DD')
      }
    } else {
      errorMessage.value = r.error || '获取详情失败'
    }
  } catch (e) {
    errorMessage.value = `请求异常：${e.message}`
  }
}
function closeApproveDialog() {
  approveDialog.value = false
  curLeave.value      = {}
  errorMessage.value  = ''
}
function closeDetailDialog() {
  detailDialog.value = false
  curLeave.value     = {}
}

/* -------------------- 审批 -------------------- */
async function approveLeave() {
  if (!curLeave.value.decision) {
    errorMessage.value = '请选择审批决定'
    return
  }
  if (!checkDateLegal()) return
  try {
    const res = await http.post('/glsb/approveLeave', curLeave.value)
    if (res.data.result === 'success') {
      closeApproveDialog()
      await getAllLeaves()
    } else {
      errorMessage.value = res.data.error || '审批提交失败'
    }
  } catch (e) {
    errorMessage.value = `审批异常：${e.message}`
  }
}
function checkDateLegal() {
  const { startDate, endDate } = curLeave.value
  const today = dayjs().format('YYYY-MM-DD')
  if (dayjs(startDate).isBefore(today)) {
    errorMessage.value = '请假开始时间不能小于当天'
    return false
  }
  if (dayjs(endDate).isBefore(startDate)) {
    errorMessage.value = '请假结束时间不能小于开始时间'
    return false
  }
  errorMessage.value = ''
  return true
}
function optOne() { approveLeave() }

/* -------------------- 分页 -------------------- */
function handlePageChange(p) {
  pageContains.pageNum = p
  getAllLeaves()
}
function handleSizeChange(s) {
  pageContains.pageSize = s
  pageContains.pageNum  = 1
  getAllLeaves()
}

/* -------------------- 标签颜色 -------------------- */
function statusTagType(status) {
  switch (status) {
    case '待审批': return 'warning'
    case '通过':   return 'success'
    case '不通过': return 'danger'
    default:       return 'info'
  }
}
</script>

<style scoped>
/* ===== 样式 ===== */
.leave-approval-container{
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}
.status-select{ width: 140px; }
.search-input{ flex: 1; max-width: 300px; }
.reset-button{
  background: #fff;
  color: #666;
  border: 1px solid #dcdfe6;
}
/*.search-button:hover,*/
/*.reset-button:hover{*/
/*  transform: translateY(-1px);*/
/*}*/
.error-message{
  color: #f56c6c;
  text-align: center;
  margin-bottom: 16px;
  height: 20px;
}
.leave-table{
  width: 100%;
  margin-bottom: 20px;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}
.table-header{
  background: #f0f2f5;
  font-weight: 600;
  color: #333;
}
.pagination-container{
  display: flex;
  justify-content: flex-end;
}
/* 与员工页完全一致 */
.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}
.status-select { width: 140px; }
.search-input  { flex: 1; max-width: 300px; }
.search-button { background: #67c23a; color: #fff; border-color: #67c23a; }
.reset-button  { background: #fff; color: #666; border: 1px solid #dcdfe6; }

/* hover 动效：统一上移 1px */
.search-button:hover,
.reset-button:hover {
  transform: translateY(-1px);
}

/* 小屏自动换行 */
@media (max-width: 768px) {
  .search-container { flex-wrap: wrap; }
}
</style>